package com.springbootblog.service.serviceImpl.fontend;

import com.springbootblog.controller.fontend.IndexController;
import com.springbootblog.dao.ArticleDao;
import com.springbootblog.pojo.ArtCategory;
import com.springbootblog.pojo.IndexArticle;
import com.springbootblog.pojo.Label;
import com.springbootblog.service.fontend.IndexService;
import com.springbootblog.utils.AES;
import com.springbootblog.utils.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class IndexServiceImpl implements IndexService
{
    /**
     * 定义一个静态常量日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 自动装载（dao接口注入）
     */
    @Autowired
    private ArticleDao articleDao;

    @Value("${spring.AES.key}")
    public String key;
    @Value("${spring.AES.iv}")
    public String iv;

    /**
     * 获取列表数据
     * @param page
     * @param search
     * @return
     */
    @Override
    public Map<String, Object> getData(Integer page, String search)
    {
        int pageSize = 9;
        // 查article表所有符合条件的数据的数量
        int articleNum = (int) articleDao.selectBySearchAndPageNum(search);
        // 计算分页信息
        Map<String, Integer> pageInfo = Function.getStartNumByPage(page, pageSize);
        int pages = pageInfo.get("page");
        int pageSizes = pageInfo.get("pageSize");
        // 查数据列表
        List<IndexArticle> articleList = articleDao.selectBySearchAndPage(search, pages, pageSizes);
        // 页码数
        int articlePage = (int) Math.ceil(articleNum / pageSize);

        for (int i = 0; i < articleList.size(); i++)
        {
            // 查评论数
            Long commentNum = articleDao.getCommentNumber(articleList.get(i).getId().toString());
            articleList.get(i).setCommentNum(String.valueOf(commentNum.intValue()));
        }
        // 定义返回值
        Map<String, Object> result = new HashMap<>(4);
        result.put("code", 200);
        result.put("dataDatanum", articleNum);
        result.put("articleShow", articleList);
        result.put("articlePage", articlePage);//*/
        return result;
    }

    /**
     * 取当前分类下的子分类，显示及查询
     * @param cate_id
     * @param cate_id_son
     * @return
     */
    public Map<String, Object> getCateId( String cate_id, String cate_id_son)
    {
        Map<String, Object> result = new HashMap<>(3);
        if(cate_id != "" && cate_id != null && !cate_id.isEmpty())
        {
            List<ArtCategory> artCategoryList = articleDao.getArtCategoryByCatePid(cate_id);
            List<String> list=new ArrayList<String>();
            for (int i = 0; i < artCategoryList.size(); i++)
            {
                String id = artCategoryList.get(i).getId().toString();
                list.add(id);
            }
            list.add(cate_id);
            result.put("cateSelect", String.join(",", list));
        }
        else if(cate_id_son != "" && cate_id_son != null && !cate_id_son.isEmpty())
        {
            ArtCategory artCategory = articleDao.getArtCategoryById(cate_id_son);
            cate_id = artCategory.getCat_pid().toString();
            result.put("cateSelect", "");
        }
        else
        {
            result.put("cateSelect", "");
        }
        List<ArtCategory> cateShow = articleDao.getArtCategoryByCatePid(cate_id);
        result.put("cateShow", cateShow);
        result.put("cate_id", cate_id);
        return result;
    }

    /**
     * 根据条件筛选文章数据
     * @param page
     * @param search
     * @param cate_id
     * @param cate_id_son
     * @param label_id
     * @return
     */
    @Override
    public Map<String, Object> getArticleListByCategory(Integer page, String search, String cate_id, String cate_id_son, String label_id ) throws Exception
    {
        // 分类id解密
        String cateIdDecrypt = AES.decryptAES(cate_id,this.key,this.iv);
        if(cateIdDecrypt != "" && cateIdDecrypt != null && !cateIdDecrypt.isEmpty())
        {
            cate_id = Function.stringToJson(cateIdDecrypt,"cate_id");
        }
        // 二级分类id解密
        String cateIdSonDecrypt = AES.decryptAES(cate_id_son,this.key,this.iv);
        if(cateIdSonDecrypt != "" && cateIdSonDecrypt != null && !cateIdSonDecrypt.isEmpty())
        {
            cate_id_son = Function.stringToJson(cateIdSonDecrypt,"cate_id_son");
        }
        // 标签id解密
        String labelIdDecrypt = AES.decryptAES(label_id,this.key,this.iv);
        if(labelIdDecrypt != "" && labelIdDecrypt != null && !labelIdDecrypt.isEmpty())
        {
            label_id = Function.stringToJson(labelIdDecrypt,"label_id");
        }
        String where = " is_show = 1 ";
        Map<String, Object> cateInfo = this.getCateId(cate_id, cate_id_son);
        // System.out.println(cateInfo.toString());
        cate_id = cateInfo.get("cate_id").toString();
        String cateSelect = cateInfo.get("cateSelect").toString();

        // 子分类列表数组
        List<ArtCategory> cateList = new ArrayList<>();
        // 分类/标签名称
        String cateName = "";

        if(!label_id.isEmpty())
        {
            where += " AND labelstr like '%," + label_id + ",%'";
            Label labelInfo = articleDao.getLabelInfoById(label_id);
            if(labelInfo.getLabelname() != null)
            {
                cateName = labelInfo.getLabelname();
            }
        }
        else if(!cate_id.isEmpty() || !cate_id_son.isEmpty())
        {
            if(!cate_id_son.isEmpty())
            {
                where += " AND art_cid = "+ cate_id_son +" ";
            }
            else if(!cate_id.isEmpty())
            {
                where += " AND art_cid IN ("+ cateSelect +") ";
            }
            // 查子分类列表
            cateList = articleDao.getArtCategoryByCatePid(cate_id);
            // 查分类名称
            ArtCategory categoryInfo = articleDao.getArtCategoryInfoById(cate_id);
            if(categoryInfo != null)
            {
                cateName = categoryInfo.getCat_name();
            }
        }
        if(search != "" && search != null && !search.isEmpty())
        {
            where += " AND arttitle like '%"+ search +"%' ";
            cateName = search;
        }
        Integer pageSize = 9;
        // 计算分页信息
        Map<String, Integer> pageInfo = Function.getStartNumByPage(page, pageSize);
        Integer startPage = pageInfo.get("page");
        Integer showNum = pageInfo.get("pageSize");
        // 文章数量
        Long articleNums = articleDao.selectSearchPageNum(where);
        // 文章列表
        List<IndexArticle> listShow = articleDao.selectSearchPage(where);
        List<IndexArticle> articleList = new ArrayList<>();
        for (int i = 0; i < listShow.size(); i++)
        {
            if(i >= startPage && i < (startPage + showNum))
            {
                articleList.add(listShow.get(i));
            }
        }
        // 页码数
        int articleNum = (int) (Math.ceil(articleNums / pageSize) - 1) + 1;
        // System.out.println("articleNum:"+(int) Math.ceil(articleNums / pageSize));
        // 文章列表(搜索文字变红)
        for (int i = 0; i < articleList.size(); i++)
        {
            articleList.get(i).setPutime(articleList.get(i).getAddtime());
            // 查评论数
            Long commentNum = articleDao.getCommentNumber(articleList.get(i).getId().toString());
            articleList.get(i).setCommentNum(String.valueOf(commentNum.intValue()));
            if(!search.isEmpty() && search != "" && search != null )
            {
                search = search.replace(" ", "");
                search = search.replace("?", "");
                search = search.replace("？", "");

                List<String> forArray = Function.usingSubstringMethod(search,search.length());
                for (int j = 0; j < forArray.size(); j++)
                {
                    String check = Function.checkLetter(forArray.get(j));
                    if(check == "big")
                    {
                        String str = forArray.get(j).toLowerCase();
                        articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace(str, "<em>" + str + "</em>"));
                    }
                    else if(check == "small")
                    {
                        String str = forArray.get(j).toUpperCase();
                        articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace(str, "<em>" + str + "</em>"));
                    }
                }
                for (int j = 0; j < forArray.size(); j++)
                {
                    // 替换标题
                    articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace("?","<em>"));
                    articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace("？","</em>"));
                    // 替换详情
                    articleList.get(i).setArtdesc(articleList.get(i).getArtdesc().replace("?","<em>"));
                    articleList.get(i).setArtdesc(articleList.get(i).getArtdesc().replace("？","</em>"));
                    // 变红
                    articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace(forArray.get(j),"<em>"+forArray.get(j)+"</em>"));
                    articleList.get(i).setArtdesc(articleList.get(i).getArtdesc().replace(forArray.get(j),"<em>"+forArray.get(j)+"</em>"));
                }
                // 替换标题
                articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace("?","<em>"));
                articleList.get(i).setArttitle(articleList.get(i).getArttitle().replace("？","</em>"));
                // 替换详情
                articleList.get(i).setArtdesc(articleList.get(i).getArtdesc().replace("?","<em>"));
                articleList.get(i).setArtdesc(articleList.get(i).getArtdesc().replace("？","</em>"));
            }
        }
        Map<String, Object> result = new HashMap<>(6);
        result.put("code",1);
        result.put("msg","操作成功！");
        result.put("articleShow",articleList);
        result.put("articlePage",articleNum);
        result.put("cateName",cateName);
        result.put("cateList",cateList);
        return result;
    }
}
